﻿$(document).ready(function() {
    // date pickers
    Date.firstDayOfWeek = 7;
    Date.format = 'mm/dd/yyyy';
    $('.date-pick').datePicker().val(new Date().asString()).trigger('change');

    // watermarks and row highlights     
    $("[watermark]").each(function() {
        this.value = $(this).attr("watermark");
        $(this).addClass("watermark");
    })
    .focus(function() {
        if (this.value === $(this).attr("watermark")) {
            this.value = "";
            $(this).removeClass("watermark");
        }
        // add row highlight
        $(this).parents(".formitem").css("background-color", "#ddd");
    })
    .blur(function() {
        if (this.value === "") {
            this.value = $(this).attr("watermark");
            $(this).addClass("watermark");
        }
        //remove row highlight
        $(this).parents(".formitem").css("background-color", "");
    });

    //remove watermark when form is submitted
    $("input:image, input:button, input:submit").click(function() {
        $(this.form.elements).select("[watermark]").each(function() {
            if (this.value === $(this).attr("watermark")) {
                this.value = "";
            }
        });
    });

    // tooltips                
    $(":text[title]").focus(function() {
        var field = $(this);
        field.after("<p id='tooltip'>" + this.title + "</p>");
        var position = field.offset();
        $("#tooltip")
            .css("top", (position.top + 10) + "px")
            .css("left", (position.left + field.width() + 10) + "px")
            .fadeIn("slow");
    })
    .blur(function() {
        $("#tooltip").remove();
    });

    var options = {
        beforeSubmit: function(formData) {
            $.blockUI();
            formData.push({ name: 'ajax_submit', value: '1' });
        },
        success: function(result) {
            $.unblockUI();
            if (result.length == 0) {
                $("#messages").empty().append("Thanks!");
            }
            else {
                var list = $("#messages").empty().append($("<ul class=\"errors\">"));
                jQuery.each(result, function(index, item) {
                    list.append($("<li>").append(item));
                });                
            }
        },
        dataType: 'json'
    };
    $("form").ajaxForm(options);
});